import React from 'react';
import ReactDOM from 'react-dom';
import {Tabs, Button, Spin} from 'antd';
import { isEqual, isEmpty } from 'lodash';
const TabPane = Tabs.TabPane;
import {WeaTools,WeaLocaleProvider} from 'ecCom';
const { ls } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
import './css/index';
import Tab4Content from './Tab4Content';
import Tab4Style from './Tab4Style';
import Tab4Share from './Tab4Share';
import ElementTemplate from './ElementTemplate';
class ESetting extends React.Component {
    state = {
        loading: false,
        canSaveTemplate: false,
    };

    constructor(props) {
        super(props);
        this.onSave = this.onSave.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.onSaveTemplate = this.onSaveTemplate.bind(this);
    }
    onSaveTemplate(){
        this.refs.ElementTemplate.onShow();
    }

    componentDidMount(){
        const {data,isSynergySetting} = this.props;
        const {ebaseid} = data
        let canSaveTemplate = true
        if(/^Custom_/.test(data.ebaseid)){
            const customCanSaveTemplate = this.refs['tab4Content'].refs[ebaseid] ? this.refs['tab4Content'].refs[ebaseid].canSaveTemplate() : false;
            canSaveTemplate = customCanSaveTemplate && data.eShareLevel == '2' && !isSynergySetting;
        }else{
            canSaveTemplate = data.eShareLevel == '2' && !isSynergySetting;
        }
        this.setState({canSaveTemplate})

    }
    render() {
        const {data, isSynergySetting, synergyParams} = this.props;
        const {loading,canSaveTemplate} = this.state;



        return (
            <div className="portal-esetting-container">
                <ElementTemplate ecId={`${this && this.props && this.props.ecId || ''}_ElementTemplate@7tswgl`} ref="ElementTemplate" eid={data.eid} templateTitle={data.eContent.eTitle} onSave={this.onSave}/>
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@5m00rd`} spinning={loading}>
                    <Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@6ra1uu`} defaultActiveKey="1" className="portal-esetting-tabs">
                        <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@ezurm5`} tab={getLabel(33368, '内容')} key="1"><Tab4Content ecId={`${this && this.props && this.props.ecId || ''}_Tab4Content@okros5`} ref="tab4Content" {...data} synergyParams={synergyParams} /></TabPane>
                        <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@1in1ew`} tab={getLabel(1014, '样式')} key="2"><Tab4Style ecId={`${this && this.props && this.props.ecId || ''}_Tab4Style@te0n13`} ref="tab4Style" {...data}/></TabPane>
                        <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@dulz6u`} tab={getLabel(119, '共享')} key="3"><Tab4Share ecId={`${this && this.props && this.props.ecId || ''}_Tab4Share@pcx8gy`} ref="tab4Share" {...data}/></TabPane>
                    </Tabs>
                    <div className="portal-esetting-confirm">
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@aqv03b`} type="primary" onClick={() => this.onSave()}>{getLabel(30986, '保存')}</Button>
                        {canSaveTemplate && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fioaeh`} type="primary" style={{marginLeft: '10px'}} onClick={this.onSaveTemplate}>{getLabel(386538, '保存并存为模板')}</Button>}
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@19gx9f`} type="ghost" style={{marginLeft: '10px'}} onClick={this.onCancel}>{getLabel(31129, '取消')}</Button>
                    </div>
                </Spin>
            </div>
        );
    }

    async onSave(params = {}, fn) {
        const {data, handleRefresh, isSetting, getElementStyle, from} = this.props;
        const {hpid, subCompanyId, eid, ebaseid, eStyle={}} = data;
        const {eHeight = ''} = eStyle;

        this.setState({loading: true});
        const contentValues = this.refs['tab4Content'] ? await this.refs['tab4Content'].getSaveValues(ebaseid) : null;
        if(!contentValues) {
            this.setState({loading: false});
            return;
        }
        // const contentValues = this.refs['tab4Content'] ? this.refs['tab4Content'].getSaveValues(ebaseid) : {};
        const styleValues = this.refs['tab4Style'] ? this.refs['tab4Style'].getSaveValues() : {};
        const shareValues = this.refs['tab4Share'] ? this.refs['tab4Share'].getSaveValues() : {};

        WeaTools.callApi('/api/portal/setting/saveSetting', 'POST', {
            jsonStr: JSON.stringify({hpid, subCompanyId, eid, ebaseid, ...contentValues, ...styleValues, ...shareValues, ...params})
        }).then(result => {
            // 刷新元素标题
            let name = jQuery(`#element_title_name_input_${eid}`).val();
            if(isSetting){// true: 门户设置页面
                jQuery('#e9PortalSetting').find(`#element_title_name_${eid}`).text(name);
            }else{
                jQuery(`#element_title_name_${eid}`).text(name);
            }
            // 刷新元素内容
            handleRefresh(eid, ebaseid);
            //刷新元素样式
            WeaTools.callApi('/api/portal/homepage/hpstyle', 'POST', {hpid: hpid,subCompanyId: subCompanyId,from:from}).then(function (result) {
                if(result && result.hpCss) {
                    let styleStr = result.hpCss.replace(/\"/g, "");
                    // if (jQuery(`#portal-element-style-${eid}`) && jQuery(`#portal-element-style-${eid}`).length) {
                    //     jQuery(`#portal-element-style-${eid}`).html(styleStr);
                    // } else {
                    //     jQuery(jQuery('head')[0]).append('<style id="portal-element-style-' + eid + '" type="text/css">' + styleStr + '</style>');
                    // }
                    if (parseInt(hpid) < 0) { // 流程表单协同可能存在多个门户
                        if (jQuery(`#portal-style-${hpid}`) && jQuery(`#portal-style-${hpid}`).length) {
                            jQuery(`#portal-style-${hpid}`).html(styleStr);
                        } else {
                            jQuery(jQuery('head')[0]).append(`<style id="portal-style-${hpid}" type="text/css">${styleStr}</style>`);
                        }
                    } else {
                        if (jQuery(`#portal-style`) && jQuery(`#portal-style`).length) {
                            jQuery(`#portal-style`).html(styleStr);
                        } else {
                            jQuery(jQuery('head')[0]).append(`<style id="portal-style" type="text/css">${styleStr}</style>`);
                        }
                    }
                    getElementStyle && getElementStyle(eid, result.fontSizeMp);
                }
            });
            !isEmpty(styleValues) && window.portalGetElementStyle({hpid, isSetting, subCompanyId, isfromportal: 1, isfromhp: 0, isSaveElement: true});
            // 卸载设置界面
            ReactDOM.render(<div></div>, $(`.homepage[data-isSetting=${this.props.isSetting}] #setting_${this.props.data.eid}`)[0]);
        });
        if(fn && typeof fn == 'function') fn();
    }

    onCancel() {
        ReactDOM.render(<div></div>, $(`.homepage[data-isSetting=${this.props.isSetting}] #setting_${this.props.data.eid}`)[0]);
    }
}

export default ESetting;
